<template>
  <div class="container" :style="containerStyle">
    <template v-if="loaded">
      <list @scroll="onPageScroll">
        <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                      :indicatorScale="indicatorScale"></page-refresh>
        <header>
          <div class="navbar" ref="navbar" :style="{backgroundColor: 'rgba(255, 255, 255, 1)', paddingTop: isWeb ? '0' : '40px'}">
            <searchbar class="flex-1" :disabled="true" @click="searchBarClick"></searchbar>
            <text v-if="iosShow"
                  :class="['navbar-btn', 'navbar-icon', 'icon', 'navbar-btn-transparent']"
                  @click="toggleSign()">&#xe617;</text>
          </div>
        </header>
        <cell>
          <div style="background-color: #fff; padding-bottom: 20px;">
            <adv-slider ref="bannerAdvList" type="ep-slider" :width="750" class="header-adv"
                        :advList="bannerAdvList"
                        borderRadius="0" :interval="6000"
                        :indicator-size="{'item-size': '20px', height: '5px', bottom: '10px'}"></adv-slider>
          </div>
        </cell>
        <cell>
          <div class="quick-nav-panel">
            <div class="quick-nav-list">
              <div class="quick-nav-list-row" v-for="(rowList, rowIdx) in quickNavRows" v-bind:key="rowIdx">
                <div class="quick-nav-list-item" v-for="(nav, navIdx) in rowList" v-bind:key="navIdx" @click="jumpPagep" :page="nav.page"
                     :params="nav.params">
                  <image :src="nav.picUrl" class="quick-nav-list-item-icon"></image>
                  <text class="quick-nav-list-item-title">{{nav.title}}</text>
                </div>
              </div>
            </div>
            <div v-if="quickNavAdvList.length > 0" class="quick-nav-adv">
              <adv-slider :width="730" :advList="quickNavAdvList"></adv-slider>
            </div>
          </div>
        </cell>
        <cell>
          <div class="floor" v-for="(floor, floorIdx) in floorList" v-bind:key="floorIdx">
            <div class="floor-heading" v-if="floor.showTitle">
              <div class="floor-heading-line-through" v-if="!floor.titlePic"></div>
              <text :class="['floor-heading-title', floor.$_titleStyle]" v-if="!floor.titlePic">{{floor.title}}</text>
              <x-image :src="floor.titlePic" v-if="floor.titlePic" :width="450"></x-image>
              <div class="floor-heading-line-through" v-if="!floor.titlePic"></div>
            </div>
            <div class="floor-body">
              <div class="floor-row" v-for="(row, rowIdx) in floor.rowList" v-bind:key="rowIdx"
                   :style="row.$_style"
                   :ref="'floor_' + floorIdx + '_row_' + rowIdx">
                <template v-for="(showcase, showcaseIdx) in row.showcaseList">
                  <div class="showcase"
                       @click="showcaseTap({page: showcase.page, params: showcase.params})"
                       v-bind:key="showcaseIdx"
                       v-if="showcase.showType === 'LIST' || !showcase.showType"
                       :ref="'floor_' + floorIdx + '_row_' + rowIdx + '_showcase_' + showcaseIdx"
                       :style="showcase.$_style">
                    <div v-if="showcase.showTitle" class="showcase-heading">
                      <text :class="['showcase-title', showcase.$_textStyle]" :style="showcase.$_titleStyle">{{showcase.title}}</text>
                      <text class="showcase-subtitle" :style="showcase.$_titleStyle">{{showcase.slogan}}</text>
                    </div>
                    <div :style="showcase.$_picWrapperStyle" v-if="showcase.pic">
                      <image :src="showcase.pic" :style="showcase.$_picStyle"></image>
                    </div>
                    <div class="showcase-body" v-if="showcase.showItem">
                      <div class="showcase-coupon-item"
                           :style="item.$_style"
                           v-for="item in showcase.commissionItemList"
                           @click="showcaseTap({itemId: item.id, page: showcase.page, params: showcase.params})"
                           v-bind:key="item.id">
                        <image :src="item.picUrl"
                               :style="item.$_picStyle"
                               class="showcase-coupon-item-pic"></image>
                        <div class="showcase-price" v-if="showcase.showPrice">
                          <text class="showcase-price-y">¥</text>
                          <text class="showcase-price-val">{{item.price.toFixed(2)}}</text>
                        </div>
                        <text class="showcase-price-small" v-if="showcase.showSalePrice">¥{{item.originPrice.toFixed(2)}}</text>
                      </div>
                    </div>
                  </div>
                  <scroller :class="['showcase', 'showcase-scroller']"
                            v-bind:key="showcaseIdx"
                            scroll-direction="horizontal"
                            v-if="showcase.showType === 'SCROLL'">
                    <div class="showcase-scroller-item"
                         @click="commissionItemClick(item)"
                         v-for="item in showcase.commissionItemList"
                         v-bind:key="item.id">
                      <image :src="item.picUrl"
                             resize="cover"
                             class="showcase-scroller-item-pic"></image>
                      <text class="showcase-scroller-item-title">{{item.title}}</text>
                      <div class="showcase-scroller-item-price-row">
                        <div class="showcase-scroller-item-price" v-if="showcase.showPrice">
                          <text class="showcase-scroller-item-price-y">¥</text>
                          <text class="showcase-scroller-item-price-val">{{item.price.toFixed(1)}}</text>
                        </div>
                        <text class="showcase-scroller-item-price-small" v-if="showcase.showSalePrice">¥{{item.originPrice.toFixed(1)}}</text>
                      </div>
                    </div>
                  </scroller>
                  <slider v-bind:key="showcaseIdx" :class="['showcase', 'showcase-slider']"
                          :style="{height: showcase.height + 'px'}"
                          infinite="false" v-if="showcase.showType === 'SLIDER'">
                    <div class="showcase-slider-column"
                         v-bind:key="itemRowListIdx"
                         v-for="(itemRowList, itemRowListIdx) in showcase.columnList">
                      <div class="showcase-slider-row"
                           v-for="(row, rowIdx) in itemRowList" v-bind:key="rowIdx">
                        <div class="showcase-slider-item"
                             :style="{width: showcase.itemWidth + 'px'}"
                             @click="commissionItemClick(item)"
                             v-for="item in row"
                             v-bind:key="item.id">
                          <template v-if="item.id">
                            <image :src="item.picUrl"
                                   resize="cover"
                                   :style="showcase.$_picStyle"
                                   class="showcase-slider-item-pic"></image>
                            <text class="showcase-slider-item-title">{{item.title}}</text>
                            <div class="showcase-slider-item-price-row">
                              <div class="showcase-slider-item-price" v-if="showcase.showPrice">
                                <text class="showcase-slider-item-price-y">¥</text>
                                <text class="showcase-slider-item-price-val">{{item.price.toFixed(1)}}</text>
                              </div>
                              <text class="showcase-slider-item-price-small" v-if="showcase.showSalePrice">¥{{item.originPrice.toFixed(1)}}</text>
                            </div>
                          </template>
                        </div>
                      </div>
                    </div>
                    <indicator class="showcase-slider-indicator"></indicator>
                  </slider>
                </template>
              </div>
            </div>
          </div>
        </cell>
        <cell ref="itemSearchFloorHeader" @disappear="itemSearchHeaderDisappear" @appear="itemSearchHeaderAppear">
          <div class="floor-heading item-list-heading" v-if="itemShowSetting.showTitle">
            <div class="floor-heading-line-through" v-if="!itemShowSetting.titlePicUrl"></div>
            <text class="floor-heading-title text-primary" v-if="!itemShowSetting.titlePicUrl">{{itemShowSetting.title}}</text>
            <x-image v-if="itemShowSetting.titlePicUrl"
                     :src="itemShowSetting.titlePicUrl" :width="450"></x-image>
            <div class="floor-heading-line-through" v-if="!itemShowSetting.titlePicUrl"></div>
          </div>
          <div v-if="itemShowSetting.shopcatBarDisplay === 'SHOW'">
            <div ref="shopcatScrollbar" class="shopcat-scrollbar">
              <shopcat-scrollbar v-on:shopcatSelected="shopcatSelected"
                                 :colorStyle="shopcatBarFixTop ? 'light' : 'default'"></shopcat-scrollbar>
            </div>
            <filterbar :param="itemSearchParam" v-on:change="filterbarChange" layout="list"
                       @layout="listLayout"></filterbar>
          </div>
        </cell>
        <cell>
          <div style="margin-top: 8px"></div>
        </cell>
        <template v-if="commissionItemList.length" v-for="(itemList, rowIdx) in commissionItemRowList">
          <item-cell @commissionItemClick="commissionItemClick" v-bind:key="rowIdx" :width="730" :border-radius="true" :layout="commissionItemListLayout"
                     :itemList="itemList"></item-cell>
        </template>
        <cell v-if="loaded && !commissionItemList.length && !hasNext">
          <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon"></page-notice>
        </cell>
        <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                           :shown="hasNext"></page-loading-more>
      </list>
      <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop" bottom="120"></page-scrolltop>
      <wxc-loading :show="loadingShow"></wxc-loading>
      <sign :show="signShow" @signHide="signHide"></sign>
    </template>
    <page-loading :loaded="loaded"></page-loading>
  </div>
</template>
<style lang="scss">
  @import "./sass/home";
  @import "./sass/floor";
  @import "./sass/utilities";
  @import "./sass/icon";
  @import "./sass/status-bar";

  $bodyWidth: 730px;

  .container-body {
    padding: 0 20px;
  }

  .container {
    /*background-color: #fff;*/
  }

  .header-adv {
    padding-top: 20px;
  }

  .header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
  }

  .quick-nav-adv {
    padding: 0 10px;
    margin-bottom: 10px;
  }

  .showcase-scroller {
    flex-direction: row;
    height: 340px;
    padding: 30px 15px;
    $width: 200px;
    &-floor-title {
      padding-top: 0;
      height: 320px;
    }
    &-item {
      width: $width;
      margin: 0 15px;
      &-pic {
        width: $width;
        height: $width;
        margin-bottom: 10px;
        border-radius: 5px;
      }
      &-title {
        font-size: 28px;
        height: 32px;
        color: $color;
        width: $width;
        /*overflow: hidden;*/
        text-overflow: ellipsis;
        margin-bottom: 10px;
      }
      &-price {
        flex-direction: row;
        align-items: flex-end;
        &-row {
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          padding: 0 3px;
        }
        &-val {
          font-size: 32px;
          color: $color-primary;
          text-align: center;
          font-weight: normal;
        }
        &-y {
          font-size: 28px;
          font-weight: lighter;
          color: $color-primary;
        }
        &-small {
          text-align: center;
          color: $color-muted;
          font-weight: 300;
          font-size: 24px;
          text-decoration: line-through;
          vertical-align: text-bottom;
        }
      }
    }
  }

  .showcase-slider {
    $width: 200px;
    width: $bodyWidth;
    position: relative;
    background-color: transparent;
    padding: 0;
    &-column {
      width: $bodyWidth;
    }
    &-indicator {
      height: 30px;
      item-color: #ddd;
      item-selected-color: $color-primary;
      item-size: 15px;
      position: absolute;
      bottom: 10px;
      left: 0;
      right: 0;
    }
    &-row {
      flex: 1;
      flex-direction: row;
      justify-content: space-between;
      margin-bottom: 3px;
      /*background-color: #fb4748;*/
    }
    &-item {
      /*flex: 1;*/
      background-color: #fff;
      padding: 20px;
      /*background-color: #fddc7a;*/
      &-pic {
        border-radius: 5px;
        /*background-color: #c822b0;*/
      }
      &-title {
        font-size: 28px;
        height: 32px;
        color: $color;
        /*overflow: hidden;*/
        text-overflow: ellipsis;
        margin-bottom: 10px ;
        /*background-color: #00B4FF;*/
        margin-top: 10px ;
      }
      &-price {
        flex-direction: row;
        align-items: flex-end;
        /*background-color: #fb4748;*/
        &-row {
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          padding: 0 3px;
        }
        &-val {
          font-size: 32px;
          color: $color-primary;
          text-align: center;
          font-weight: normal;
        }
        &-y {
          font-size: 28px;
          font-weight: lighter;
          color: $color-primary;
        }
        &-small {
          text-align: center;
          color: $color-muted;
          font-weight: 300;
          font-size: 24px;
          text-decoration: line-through;
          vertical-align: text-bottom;
        }
      }
    }
  }
</style>
<script>
import {WxcLoading, Utils} from 'weex-ui'
let api = require('./include/api')
let grouping = require('./include/grouping')
let shuffle = require('./include/shuffle')
let bodyWidth = 730
let SHOWCASE_FLOOR_WIDTH = bodyWidth
let SHOWCASE_ITEM_MARGIN = 3
let textStyles = ['text-info', 'text-success', 'text-warning', 'text-primary', 'text-pink', 'text-purple',
  'text-sky', 'text-orange']
let Deferred = require('Deferred')
let dom = weex.requireModule('dom')
let urlPath = require('./include/url-path')
let modal = weex.requireModule('modal')
let navigator = require('./include/xnavigator')
let jumpPage = require('./include/page-jump')
let config = require('./include/app-config')
let pageCache = require('./include/page-cache')

// let SCREEN_SCALA = weex.config.env.deviceWidth / 750
let DEFAULT_NAVBAR_ICON_OPACITY = 0.5
let PAGE_DATA_CACHE_KEY = 'HOME_DATA_V1'
let PAGE_ITEM_CACHE_KEY = 'HOME_ITEM_V1'
const DEFAULT_ITEM_SEARCH_PARAM = {
  page: 1,
  sort: 'NONE',
  keywords: '',
  ecomPlat: '',
  startPrice: '',
  endPrice: ''
}
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-loading-more'),
    require('./mixin/page-scrolltop'),
    require('./mixin/page-loading'),
    require('./include/page-cache')
  ],
  components: {
    WxcLoading,
    'commission-item-list': require('./components/commission-item-list.vue'),
    'shopcat-scrollbar': require('./components/shopcat-scrollbar.vue'),
    'page-notice': require('./components/page-notice.vue'),
    'searchbar': require('./components/searchbar.vue'),
    'filterbar': require('./components/filterbar.vue'),
    'item-cell': require('./components/commission-item-cell.vue'),
    sign: require('./components/sign.vue'),
    'adv-slider': require('./components/adv-slider.vue'),
    'x-image': require('./components/x-image.vue')
  },
  props: {
    height: {default: 0}
  },
  data () {
    return {
      bannerAdvList: [],
      isWeb: Utils.env.isWeb(),
      quickNavRows: [],
      floorList: [],
      showcaseItemSmallWidth: 0,
      showcaseItemLargeWidth: 0,
      commissionItemList: [],
      commissionItemRowList: [],
      refreshing: false,
      refreshIndicatorScale: 0.2,
      hasNext: true,
      shopcatId: '',
      sorryIcon: 'images/aiya.png',
      topbarHide: false,
      logo: 'images/logo.png?v=1',
      shopcatBarFixTop: false,
      itemSearchParam: Object.assign({}, DEFAULT_ITEM_SEARCH_PARAM),
      containerStyle: {},
      loadingShow: false,
      signShow: false,
      scrollOffsetY: 0,
      navbarOpacity: 0,
      navbarIconOpacity: DEFAULT_NAVBAR_ICON_OPACITY,
      showStatusBar: false,
      showcaseMargin: 5,
      itemListTitlePic: urlPath.assets('images/index/item_list_title.png'),
      commissionItemListLayout: 'list',
      itemShowSetting: {},
      itemSearchFloorAffixTop: false,
      itemSearchHeaderShow: false,
      quickNavAdvList: [],
      loadTimes: 0,
      iosShow: false
    }
  },
  mounted: function () {
  },
  created () {
    config.bindConfig(this)
    if (this.height) {
      this.containerStyle.height = this.height
    }
    this.showcaseItemSmallWidth = (SHOWCASE_FLOOR_WIDTH / 2 - 16 * 4) / 3
    this.showcaseItemLargeWidth = this.showcaseItemSmallWidth + 20
    this.sorryIcon = urlPath.assets(this.sorryIcon)
    this.logo = urlPath.assets(this.logo)

    pageCache.cache(PAGE_DATA_CACHE_KEY).done(rs => {
      if (rs) {
        this.handleData(rs)
        this.loaded = true
      }
    })
    pageCache.cache(PAGE_ITEM_CACHE_KEY).done(rs => {
      if (rs) {
        this.handleItemSearchData(rs)
      }
    })
    setTimeout(() => {
      this.loadData().done(rs => {
        this.loaded = true
      })
      this.searchItem()
    }, 200)
  },
  methods: {
    loadData (lazyUpdate) {
      return api.page.index.data().done((rs) => {
        this.handleData(rs)
        pageCache.cache(PAGE_DATA_CACHE_KEY, rs)
      }).fail(() => {
        if (this.loadTimes++ >= 3) {
          setTimeout(() => {
            this.loadData()
          }, 500)
        }
      })
    },
    handleData (rs) {
      let data = rs.data
      this.bannerAdvList = data.banner.advList
      this.quickNavRows = grouping(data.quickNavList, 5)
      this.quickNavAdvList = data.quickNavAdvList
      this.floorList = data.floorList
      shuffle(textStyles)
      this.handleFloor()
      this.cleanShowcase()
      this.itemShowSetting = data.itemShowSetting
      this.itemSearchParam = data.itemShowSetting.searchParam
      if (this.itemShowSetting.listType === 'ALTERNATE') {
        this.commissionItemListLayout = new Date().getDate() % 2 === 1 ? 'list' : 'grid'
      } else {
        this.commissionItemListLayout = this.itemShowSetting.listType.toLowerCase()
      }
    },
    handleFloor () {
      for (var idx in this.floorList) {
        this.floorList[idx].$_titleStyle = textStyles[idx % textStyles.length]
        let floor = this.floorList[idx]
        if (floor.titlePic) {
          floor.$_titlePicStyle = this.detectFloorTitlePicStyle(floor.titlePicWidth, floor.titlePicHeight)
        }
        for (var rowIdx in floor.rowList) {
          let row = floor.rowList[rowIdx]
          let rowHeightList = [0]
          let rowWidth = SHOWCASE_FLOOR_WIDTH - (row.showcaseList.length - 1) * SHOWCASE_ITEM_MARGIN // 两个showcase之间的距离为3
          for (var showcaseIdx in row.showcaseList) {
            var showcaseHeight = 0
            let showcase = row.showcaseList[showcaseIdx]
            if (showcase.showTitle) {
              showcaseHeight += 78 // heading的高度
              showcaseHeight += 10 // margin-bottom的高度
            }
            showcaseHeight += 20 // padding-bottom 20
            showcase.$_titleStyle = this.detectTitleShowcaseStyle(showcase)
            showcase.$_style = {width: rowWidth * showcase.width / 100 + 'px'}
            if (showcase.pic) {
              showcase.$_picWrapperStyle = this.detectShowcasePicWrapperStyle(showcase)
              showcase.$_picStyle = this.detectShowcasePicStyle(showcase)
              rowHeightList.push(showcase.$_picStyle.heightVal)
              continue
            }
            if (showcase.showType === 'LIST') {
              if (showcase.showItem) {
                let itemPicStyle = {
                  width: (showcase.commissionItemList.length >= 3 ? this.showcaseItemSmallWidth
                    : this.showcaseItemLargeWidth) + 'px',
                  height: (showcase.commissionItemList.length >= 3
                    ? this.showcaseItemSmallWidth : this.showcaseItemLargeWidth)
                }
                for (var itemIdx in showcase.commissionItemList) {
                  var commissionItem = showcase.commissionItemList[itemIdx]
                  commissionItem.$_picStyle = itemPicStyle
                  commissionItem.$_style = itemPicStyle
                }
                showcaseHeight += itemPicStyle.height // showcase 的的宽度减去body的padding 加上item的高度
                itemPicStyle.height += 'px'

                if (showcase.showPrice) {
                  showcaseHeight += 30 // 价格的高度
                }
                if (showcase.showSalePrice) {
                  showcaseHeight += 22 // 原价的高度
                }
              }
            } else if (showcase.showType === 'SLIDER') {
              let columnItemNum = showcase.rowItemNum * showcase.rowNum
              let rowItemWidth = (rowWidth - (showcase.rowItemNum - 1) * 3) / showcase.rowItemNum
              showcase.rowItemWidth = rowItemWidth
              let columnItemList = grouping(showcase.commissionItemList, columnItemNum, true)
              showcase.columnList = []
              for (var i in columnItemList) {
                let itemList = columnItemList[i]
                showcase.columnList.push(grouping(itemList, showcase.rowItemNum, true))
              }

              showcase.itemWidth = (SHOWCASE_FLOOR_WIDTH - (showcase.rowItemNum - 1) * SHOWCASE_ITEM_MARGIN) / showcase.rowItemNum
              let showcasePicWidth = showcase.itemWidth - 40 // 减去item的padding
              showcase.$_picStyle = {
                width: showcasePicWidth + 'px',
                height: showcasePicWidth + 'px'
              }
              var showcaseRowHeight = showcasePicWidth + 40 // item的padding,row的margin-bottom

              /**
               * 商品标题
               * */
              showcaseRowHeight += 32 // 高度
              showcaseRowHeight += 20 // margin
              /**
               * 商品标题
               * */

              if (showcase.showPrice) {
                showcaseRowHeight += 32
              }
              showcaseHeight += 40 // showcase的padding
              showcaseHeight = showcaseRowHeight * showcase.rowNum + SHOWCASE_ITEM_MARGIN * (showcase.rowNum - 1)
            }
            rowHeightList.push(showcaseHeight)
          }
          row.$_style = {
            height: Math.max.apply(null, rowHeightList) + 'px'
          }
        }
      }
    },
    listLayout (layout) {
      this.commissionItemListLayout = layout
    },
    detectFloorRowStyle (row) {
      if (weex.config.env.platform.toUpperCase() === 'ANDROID') {
        return {
          height: row.height
        }
      } else {
        return {}
      }
    },
    loadUserRedPacket () {
      api.userRedPacket.list().done(rs => {
        // modal.alert({message: JSON.stringify(rs)})
      })
    },
    randomTextStyle () {
      return textStyles[parseInt(Math.random() * 100) % textStyles.length]
    },
    cleanShowcase () {
      var self = this
      shuffle(textStyles)
      var idx = 0
      self.floorList.forEach((floor) => {
        floor.rowList.forEach((row) => {
          row.showcaseList.forEach((showcase, i) => {
            showcase.$_textStyle = textStyles[(idx++) % textStyles.length]
          })
        })
      })
    },
    handleScrollTop () {
      // if(this.itemShowSetting.shopcatBarDisplay === 'AFFIX_TOP' ) {
      //   dom.getComponentRect(this.$refs.itemSearchFloorHeader, (res) => {
      //     if(res.result) {
      //       if(res.size.top <= 180 && this.itemSearchHeaderShow
      //         && this.scrollOffsetY <= -300) {
      //         this.itemSearchFloorAffixTop = true
      //       } else {
      //         this.itemSearchFloorAffixTop = false
      //       }
      //     }
      //   })
      // }
      if (this.scrollOffsetY >= -10) {
        this.navbarOpacity = 0
        this.navbarIconOpacity = DEFAULT_NAVBAR_ICON_OPACITY
      } else {
        let offsetY = -300
        let opacity = this.scrollOffsetY / offsetY
        let navbarIconOpacity = 1 - opacity
        if (navbarIconOpacity < 0) {
          navbarIconOpacity = 0
        }
        if (navbarIconOpacity < DEFAULT_NAVBAR_ICON_OPACITY) {
          this.navbarIconOpacity = navbarIconOpacity
        } else {
          this.navbarIconOpacity = DEFAULT_NAVBAR_ICON_OPACITY
        }
        if (opacity <= 1) {
          this.navbarOpacity = opacity
        } else if (this.navbarOpacity !== 1) {
          this.navbarOpacity = 1
        }
      }
    },
    resetSearchParam () {
      // Object.assign(this.itemSearchParam, DEFAULT_ITEM_SEARCH_PARAM)
      this.hasNext = true
    },
    searchItem (append, callback) {
      for (var key in this.itemSearchParam) {
        if (this.itemSearchParam[key] === null) {
          delete this.itemSearchParam[key]
        }
      }
      // modal.alert({message: JSON.stringify(this.itemSearchParam)})
      return api.search.commissionItem(this.itemSearchParam).done((rs) => {
        this.handleItemSearchData(rs, append)
        if (this.itemSearchParam.page === 1) {
          pageCache.cache(PAGE_ITEM_CACHE_KEY, rs)
        }
      }).always(() => {
        callback && callback()
      })
    },
    handleItemSearchData (rs, append) {
      if (append) {
        this.commissionItemList = this.commissionItemList.concat(rs.data.results)
      } else {
        this.commissionItemList = rs.data.results
      }
      this.commissionItemRowList = grouping(this.commissionItemList, 2)
      let paging = rs.data
      this.hasNext = paging.hasNext
    },
    itemSearchHeaderDisappear () {
      this.itemSearchHeaderShow = false
    },
    itemSearchHeaderAppear () {
      this.itemSearchHeaderShow = true
    },
    onXRefresh (event) {
      // this.resetSearchParam()
      this.onRefresh(event, Deferred.when(this.loadData(true).done(() => {
        this.searchItem()
      })))
      // this.$refs.homePopup.detect()
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.itemSearchParam.page = this.itemSearchParam.page + 1
      this.searchItem(true, () => {
        this.loadingMore = false
      })
    },
    toggleSign () {
      this.signShow = !this.signShow
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.bannerAdvList)
    },
    detectFloorTitlePicStyle (width, height) {
      let maxWidth = SHOWCASE_FLOOR_WIDTH / 2
      return {
        width: maxWidth + 'px',
        height: (height * maxWidth / width) + 'px'
      }
    },
    detectTitleShowcaseStyle (showcase) {
      let style = {}
      if (showcase.alignCenter) {
        style.textAlign = 'center'
      }
      return style
    },
    detectShowcasePicStyle (showcase) {
      let width = showcase.width * SHOWCASE_FLOOR_WIDTH / 100
      if (showcase.picWidth < width) {
        return {
          width: showcase.picWidth + 'px',
          height: showcase.picHeight + 'px',
          heightVal: showcase.picHeight
        }
      }
      return {
        width: width + 'px',
        height: showcase.picHeight * width / showcase.picWidth + 'px',
        heightVal: showcase.picHeight * width / showcase.picWidth
      }
    },
    detectShowcasePicWrapperStyle (showcase) {
      let style = {}
      switch (showcase.picLayout) {
        case 'COVER':
          style = {}
          return style
        case 'LEFT':
          style = {
            'align-items': 'flex-start'
          }
          break
        case 'CENTER':
          style = {
            'align-items': 'center'
          }
          break
        case 'RIGHT':
          style = {
            'align-items': 'flex-end'
          }
          break
      }
      style.padding = 16 + 'px'
      return style
    },
    shopcatSelected (shopcat) {
      this.resetSearchParam()
      this.itemSearchParam.catIds = shopcat.id || ''
      this.loadingShow = true
      this.searchItem(false, rs => {
        this.loadingShow = false
      })
    },
    onPageScroll (event) {
      this.scrollOffsetY = event.contentOffset.y
      // this.handleScrollTop()
      this.onPageScrollForScrollTop(event)
    },
    filterbarChange () {
      this.loadingShow = true
      this.searchItem(false, rs => {
        setTimeout(() => {
          dom.scrollToElement(this.$refs.top)
        }, 1)
        this.loadingShow = false
      })
    },
    commissionItemClick (item) {
      if (item.id) {
        navigator.push('commission-item.js?id=' + item.id)
      } else {
        navigator.push('commission-item.js?sourceItemId=' + item.sourceItemId + '&ecomPlat=' + item.ecomPlat)
      }
    },
    jumpPagep (e) {
      let attr = e.target.attr
      jumpPage({
        page: attr.page,
        params: attr.params
      })
    },
    showcaseTap (obj) {
      let list = []
      if (obj.itemId) {
        list.push('itemIds=' + obj.itemId)
      }
      if (obj.params) {
        list.push(obj.params)
      }
      jumpPage({
        page: obj.page,
        params: list.join('&')
      })
    },
    searchBarClick () {
      navigator.push('search.js')
    },
    signHide () {
      this.signShow = false
    }
  }
}
</script>
